package com.dl.dlcommon.interceptor;

import com.dl.dlcommon.utils.result.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author DL
 * @create 2025-03-14 16:19
 */
// 使用 ResponseBodyAdvice 来包装成功的响应
@ControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 返回 true 表示需要包装
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        System.out.println("body = " + (body != null ? body.toString() : null));
        if (body instanceof Result) {
            // 如果已经是 ResponseResult 类型，则不进行包装
            return body;
        }
        // 包装返回结果
        Result<?> result = Result.ok(body);

        // 如果返回值是 String 类型，则手动序列化为 JSON 字符串
        if (body instanceof String) {
            try {
                return new ObjectMapper().writeValueAsString(result);
            } catch (Exception e) {
                throw new RuntimeException("Failed to serialize Result to JSON", e);
            }
        }

        return result;
    }
}
